/*
 * This file is part of the JNR project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.liuyun.unixsocket;

import jnr.unixsocket.UnixSocketAddress;
import jnr.unixsocket.UnixSocketChannel;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author liuyun
 */
public class UnixClient {
    private static final Logger LOGGER = Logger.getLogger(UnixClient.class.getName());

    public static final String SOCK_FILE = "/tmp/test.sock";


    public static void main(String[] args) throws IOException, InterruptedException {
        LOGGER.info("启动client...");
        java.io.File path = new java.io.File(SOCK_FILE);
        int retries = 0;
        while (!path.exists()) {
            TimeUnit.MILLISECONDS.sleep(500L);
            retries++;
            if (retries > 10) {
                throw new IOException(String.format("File %s does not exist after retry", path.getAbsolutePath()));
            }
        }
        String data = " time(" + LocalDateTime.now() + ") : this message is from client...";
        UnixSocketAddress address = new UnixSocketAddress(path);
        UnixSocketChannel channel = UnixSocketChannel.open(address);
        LOGGER.info("connected to " + channel.getRemoteSocketAddress());
        try (PrintWriter w = new PrintWriter(Channels.newOutputStream(channel));
             InputStreamReader r = new InputStreamReader(Channels.newInputStream(channel))) {
            w.print(data);
            w.flush();

            CharBuffer result = CharBuffer.allocate(1024);
            r.read(result);
            result.flip();
            LOGGER.log(Level.INFO, "read from server: {0}", result);
            final int status;
            if (!result.toString().equals(data)) {
                LOGGER.info("ERROR: data mismatch");
                status = -1;
            } else {
                LOGGER.info("SUCCESS");
                status = 0;
            }
            System.exit(status);
        }

    }
}
